class Solution {
public:
    struct node {
        int cnt, day;
        bool operator<(const node& p1) const { return day > p1.day; }
    };
    int eatenApples(vector<int>& apples, vector<int>& days) {
        int ret = 0, maxn = 0;
        priority_queue<node, vector<node>> q;
        int i = 0;
        for (; i < apples.size(); i++) {
            if (apples[i] != 0)
                q.push({apples[i], i + days[i]});
            maxn = max(maxn, i + days[i]);
            while (q.size() && q.top().day <= i)
                q.pop();
            if (q.empty())
                continue;
            auto t = q.top();
            q.pop();
            ret++;
            t.cnt--;
            if (t.cnt > 0)
                q.push(t);
        }
        for (; i < maxn; i++) {
            while (q.size() && q.top().day <= i)
                q.pop();
            if (q.empty())
                continue;
            auto t = q.top();
            q.pop();
            ret++;
            t.cnt--;
            if (t.cnt > 0)
                q.push(t);
        }
        return ret;
    }
};
